#!/bin/bash

# Launches a local docker container that will have a PSQL DB on it.
# Note, it takes a few seconds for database to initialize after running
# this script. Once initializated then 'run_flyway' can be run to install
# schema and tables.

set -eu
function stop_container() {
  echo "Stopping docker..."
  local runningContainerId=$(docker container ls | grep triplea-lobby-db | cut -f 1 -d ' ')
  if [ ! -z "$runningContainerId" ]; then
     docker container stop $runningContainerId > /dev/null
     docker container rm $runningContainerId > /dev/null
  fi
}


function remove_dead_containers() {
  docker ps --filter "status=exited" | grep triplea-lobby-db | cut -d ' ' -f 1 | \
	  xargs --no-run-if-empty docker rm
}

function start_container() {
  echo "Starting docker..."
  docker run -d --name=triplea-lobby-db -p 5432:5432 triplea/lobby-db > /dev/null
}

stop_container
remove_dead_containers
start_container
